<template>
	<view id="app">
		<view class="container fdc">
			<view class="df fdc bgw">
				<view class="f30 c000 fw4 ptb20 bdb1s brcce  pl15">工具图集上传</view>
				<view class="ptb15  pl15">
					<uv-upload
						:fileList="fileList1"
						name="1"
						multiple 
						:maxCount="15"
						@afterRead="afterRead" 
						@delete="deletePic" 
					></uv-upload>
				</view>
			</view>
			<view class="df fdc aic mt20">
				<view class="btn">
					<uv-button color="#145cfe" iconColor="#fff" @click="submitTools()" text="提交"></uv-button>
				</view>
			</view>
		</view>
		
	</view>
</template>

<script>
	let that;
	export default {
		data() {
			return {
				fileList1:[],
			}
		},
		onLoad(){
			that = this;
			this.getTools();
		},
		methods: {
			submitTools:function(){
				if(this.fileList1.length == 0){
					this.alert('请上传工具图');
					return false;
				}
				let images = [];
				this.fileList1.map((item)=>{
					console.log(item);
					images.push(item.url);
				});
				this.request({
					url:"/api/user/toolsedit",
					data:{images:images.join(',')},
					success:function(rlt){
						if(rlt.code == 200){
							this.alert('上传成功');
						}
					}
				})
			},
			getTools:function(){
				this.request({
					url:"/api/user/tools",
					success:function(rlt){
						if(rlt.code == 200){
							if(rlt.data.length >0){
								rlt.data.map(function(item){
									that.fileList1.push({
										url:item
									});
								})
							}
						}
					}
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					let res = await this.getToken(lists[i].url);
					const result = await this.uploadfile(lists[i].url,res)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadfile:function(url,res){
				return new Promise((resolve, reject) => {
					let imgurl = '';
					this.qnUpload.upload(url,function(rlt){
						imgurl = rlt.imageURL
						
					},function(e){
					},{
						region: 'NCN',
						uptoken: res.data.token,
						key:res.data.filename,
					});
					setTimeout(() => {
						resolve(res.data.cdnurl+imgurl);
					}, 1000)
				})
			},
			getToken(e){
				console.log(e);
				return this.request({url:"/api/common/qntoken",data:{'file':e}});
			},
		}
	}
</script>

<style lang="less" scoped>
.btn{width:480rpx;}
</style>
